<template>
  <div class="user-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">用户管理</h1>
          <p class="page-subtitle">管理系统用户及其状态信息</p>
        </div>
        <div class="header-actions">
          <div class="selection-info" v-if="selectedUsers.length > 0">
            <el-tag type="warning" size="small">
              已选择 {{ selectedUsers.length }} 个用户
            </el-tag>
          </div>
          <el-button type="warning" size="large" @click="handleBatchResetPassword" :disabled="selectedUsers.length === 0">
            <el-icon><Key /></el-icon>
            批量重置密码
          </el-button>
          <el-button type="primary" size="large" @click="handleAddUser">
            <el-icon><Plus /></el-icon>
            新增用户
          </el-button>
        </div>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-card class="search-card">
        <div class="search-form">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="8" :lg="6">
              <div class="search-item">
                <label class="search-label">用户名</label>
                <el-input
                  v-model="searchForm.username"
                  placeholder="请输入用户名"
                  clearable
                  :prefix-icon="Search"
                />
              </div>
            </el-col>
            <el-col :xs="24" :sm="8" :lg="6">
              <div class="search-item">
                <label class="search-label">邮箱地址</label>
                <el-input
                  v-model="searchForm.email"
                  placeholder="请输入邮箱"
                  clearable
                  :prefix-icon="Message"
                />
              </div>
            </el-col>
            <el-col :xs="24" :sm="8" :lg="6">
              <div class="search-item">
                <label class="search-label">用户状态</label>
                <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 100%">
                  <el-option label="全部" value="" />
                  <el-option label="启用" value="active" />
                  <el-option label="禁用" value="inactive" />
                </el-select>
              </div>
            </el-col>
            <el-col :xs="24" :sm="8" :lg="6">
              <div class="search-item">
                <label class="search-label">用户角色</label>
                <el-select v-model="searchForm.role_key" placeholder="请选择角色" clearable style="width: 100%">
                  <el-option label="全部" value="" />
                  <el-option
                    v-for="role in roleOptions"
                    :key="role.value"
                    :label="role.label"
                    :value="role.value"
                  />
                </el-select>
              </div>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="6">
              <div class="search-actions">
                <el-button type="primary" @click="handleSearch" :loading="loading">
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
                <el-button @click="handleReset">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>

    <!-- 主要内容区域 -->
    <div class="content-section">
      <el-card class="table-card">
        <el-table
          :data="userList"
          style="width: 100%"
          v-loading="loading"
          @selection-change="handleSelectionChange"
          :header-cell-style="{
            background: '#f8fafc',
            color: '#475569',
            fontWeight: '600',
            fontSize: '14px'
          }"
          :row-style="{ height: '64px' }"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="username" label="用户名" width="200">
            <template #default="{ row }">
              <div class="user-info">
                <el-avatar :size="32" :src="row.avatar" class="user-avatar">
                  <el-icon><User /></el-icon>
                </el-avatar>
                <span class="username">{{ row.username }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱" show-overflow-tooltip width="200" />
          <el-table-column prop="role_name" label="角色" width="120">
            <template #default="{ row }">
              <div class="role-info">
                <el-tag 
                  :type="getRoleTagType(row.role_key)" 
                  size="small" 
                  class="role-tag"
                >
                  {{ getRoleDisplayName(row.role_key) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="is_active" label="状态" width="120" align="center">
            <template #default="{ row }">
              <el-tag
                :type="row.is_active ? 'success' : 'danger'"
                size="small"
                class="status-tag"
              >
                {{ row.is_active ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="date_joined" label="创建时间" width="180">
            <template #default="{ row }">
              <div class="time-info">
                <el-icon class="time-icon"><Clock /></el-icon>
                <span>{{ row.date_joined }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作"  fixed="right" align="center">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button size="small" type="primary" plain @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button
                  size="small"
                  :type="row.is_active ? 'warning' : 'success'"
                  plain
                  @click="handleToggleStatus(row)"
                >
                  <el-icon><component :is="row.is_active ? 'CircleClose' : 'CircleCheck'" /></el-icon>
                  {{ row.is_active ? '禁用' : '启用' }}
                </el-button>
                <el-button
                  size="small"
                  type="info"
                  plain
                  @click="handleResetPassword(row)"
                >
                  <el-icon><Key /></el-icon>
                  重置密码
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  plain
                  @click="handleDelete(row)"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
          />
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="600px"
      class="user-dialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
        label-position="top"
        class="user-form"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色" prop="role_key">
              <el-select v-model="userForm.role_key" placeholder="请选择角色" style="width: 100%">
                <el-option
                  v-for="opt in roleOptions"
                  :key="opt.value"
                  :label="opt.label"
                  :value="opt.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="dialogType === 'add'">
            <el-form-item label="密码" prop="password">
              <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="dialogType === 'edit'">
          <el-col :span="12">
            <el-form-item label="邮箱地址">
              <el-input v-model="userForm.email" placeholder="请输入邮箱地址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="用户状态">
          <el-switch
            v-model="userForm.is_active"
            active-text="启用"
            inactive-text="禁用"
            :active-value="true"
            :inactive-value="false"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button size="large" @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" size="large" @click="handleSubmit" :loading="submitLoading">
            {{ dialogType === 'add' ? '创建用户' : '保存修改' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Message, Refresh, User, Clock, Edit, CircleClose, CircleCheck, Key, Delete, Warning } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { getRoleList, type Role } from '@/api/role'

const userStore = useUserStore()

// 搜索表单
const searchForm = reactive({
  username: '',
  email: '',
  status: '',
  role_key: '' // 新增角色筛选
})

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 用户列表
const userList = ref<any[]>([])
const loading = ref(false)

// 选中的用户
const selectedUsers = ref<any[]>([])

// 对话框
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const userFormRef = ref()

// 提交加载状态
const submitLoading = ref(false)

// 用户表单
const userForm = reactive({
  id: undefined,
  username: '',
  role_key: '',
  password: '',
  email: '',
  is_active: true
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  role_key: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 角色下拉选项（从API动态获取）
const roleOptions = ref<{ label: string; value: string }[]>([])
const roleList = ref<Role[]>([])

// 获取角色列表
const fetchRoles = async () => {
  try {
    const response = await getRoleList({ page_size: 100 }) // 获取所有角色
    if (response.code === 200) {
      roleList.value = response.data.results
      roleOptions.value = response.data.results.map(role => ({
        label: role.name,
        value: role.key
      }))
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 获取角色显示名称
const getRoleDisplayName = (roleKey: string) => {
  const role = roleList.value.find(r => r.key === roleKey)
  return role ? role.name : roleKey
}

// 获取角色标签类型
const getRoleTagType = (roleKey: string) => {
  const role = roleList.value.find(r => r.key === roleKey)
  if (!role) return 'info'
  
  // 根据角色标识返回不同的标签类型
  switch (roleKey) {
    case 'admin':
      return 'danger'
    case 'manager':
      return 'warning'
    case 'member':
      return 'success'
    default:
      return 'info'
  }
}

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    // 将前端状态值映射为后端所需的 0/1 字符串
    const mappedStatus =
      searchForm.status === 'active' ? '0' : searchForm.status === 'inactive' ? '1' : ''

    const params = {
      page: pagination.current,
      page_size: pagination.pageSize,
      username: searchForm.username,
      email: searchForm.email,
      status: mappedStatus,
      role_key: searchForm.role_key
    }
    const res = await userStore.getAdminUsers(params)
    userList.value = res.results || []
    pagination.total = res.count || 0
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchUsers()
}

// 重置
const handleReset = () => {
  searchForm.username = ''
  searchForm.email = ''
  searchForm.status = ''
  searchForm.role_key = '' // 重置角色筛选
  handleSearch()
}

// 新增用户
const handleAddUser = () => {
  dialogType.value = 'add'
  userForm.id = undefined
  userForm.username = ''
  userForm.role_key = ''
  userForm.email = ''
  userForm.password = ''
  userForm.is_active = true
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row: any) => {
  dialogType.value = 'edit'
  userForm.id = row.id
  userForm.username = row.username
  userForm.role_key = row.role_key
  userForm.email = row.email || ''
  userForm.password = ''
  userForm.is_active = row.is_active
  dialogVisible.value = true
}

// 切换用户状态
const handleToggleStatus = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.is_active ? '禁用' : '启用'}该用户吗？`,
      '提示',
      { type: 'warning' }
    )

    await userStore.toggleAdminUserStatus(row.id)
    row.is_active = !row.is_active
    ElMessage.success('操作成功')
  } catch (error) {
    console.log('取消操作')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await userFormRef.value.validate()

    submitLoading.value = true

    if (dialogType.value === 'add') {
      await userStore.createAdminUser({
        username: userForm.username,
        password: userForm.password,
        role_key: userForm.role_key,
        is_active: userForm.is_active
      })
      ElMessage.success('用户创建成功')
    } else {
      if (!userForm.id && userForm.id !== 0) {
        ElMessage.error('缺少用户ID，无法更新')
        submitLoading.value = false
        return
      }
      await userStore.updateAdminUser(Number(userForm.id), {
        role_key: userForm.role_key,
        email: userForm.email,
        is_active: userForm.is_active
      })
      ElMessage.success('用户更新成功')
    }

    dialogVisible.value = false
    fetchUsers()
    
    // 触发全局事件，通知其他组件用户数据已更新
    window.dispatchEvent(new CustomEvent('userDataUpdated'))
  } catch (error: any) {
    // 区分前端表单校验错误与后端API返回的错误
    const backendMsg = error?.response?.data?.message || error?.response?.data?.detail
    if (backendMsg) {
      ElMessage.error(backendMsg)
    } else if (error?.name === 'ElFormError' || /validate/i.test(String(error))) {
      ElMessage.error('请按提示修正表单后重试')
    } else if (error?.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('操作失败，请稍后重试')
    }
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 分页变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  fetchUsers()
}

const handleCurrentChange = (val: number) => {
  pagination.current = val
  fetchUsers()
}

// 重置密码
const handleResetPassword = async (row: any) => {
  try {
    // 显示确认对话框，提供更详细的信息
    await ElMessageBox.confirm(
      `<div style="text-align: left;">
        <p><strong>确定要重置用户密码吗？</strong></p>
        <p>用户名：${row.username}</p>
        <p>邮箱：${row.email || '未设置'}</p>
        <p style="color: #e6a23c; margin-top: 10px;">
          <el-icon><Warning /></el-icon>
          重置后密码将变为：<strong style="color: #f56c6c;">123456</strong>
        </p>
        <p style="color: #909399; font-size: 12px; margin-top: 8px;">
          请提醒用户及时修改密码以确保账户安全
        </p>
      </div>`,
      '重置密码确认',
      { 
        type: 'warning',
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确认重置',
        cancelButtonText: '取消',
        customClass: 'reset-password-dialog'
      }
    )

    // 显示加载状态
    const loadingInstance = ElMessage({
      message: '正在重置密码...',
      type: 'info',
      duration: 0,
      showClose: false
    })

    try {
      await userStore.resetAdminUserPassword(row.id)
      
      // 关闭加载提示
      loadingInstance.close()
      
      // 显示成功消息，并提供复制密码选项
      ElMessage({
        message: `用户 "${row.username}" 的密码已成功重置为 123456`,
        type: 'success',
        duration: 5000,
        showClose: true
      })
      
      // 询问是否复制密码到剪贴板
      try {
        await ElMessageBox.confirm(
          '密码重置成功！是否将新密码复制到剪贴板？',
          '复制密码',
          {
            confirmButtonText: '复制密码',
            cancelButtonText: '取消',
            type: 'info'
          }
        )
        
        // 复制密码到剪贴板
        if (navigator.clipboard) {
          await navigator.clipboard.writeText('123456')
          ElMessage.success('密码已复制到剪贴板')
        } else {
          // 降级方案：使用传统方法复制
          const textArea = document.createElement('textarea')
          textArea.value = '123456'
          document.body.appendChild(textArea)
          textArea.select()
          document.execCommand('copy')
          document.body.removeChild(textArea)
          ElMessage.success('密码已复制到剪贴板')
        }
      } catch (copyError) {
        // 用户取消复制操作，不显示错误
        console.log('用户取消复制密码')
      }
      
      // 可选：记录操作日志
      console.log(`管理员重置了用户 ${row.username} 的密码`)
      
    } catch (apiError: any) {
      // 关闭加载提示
      loadingInstance.close()
      
      // 处理API错误
      const errorMessage = apiError?.response?.data?.message || 
                          apiError?.message || 
                          '重置密码失败，请稍后重试'
      ElMessage.error(errorMessage)
      console.error('重置密码API错误:', apiError)
    }
    
  } catch (error) {
    // 用户取消操作
    if (error !== 'cancel') {
      console.error('重置密码操作异常:', error)
      ElMessage.error('操作异常，请稍后重试')
    }
  }
}

// 删除用户
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `删除后不可恢复，确定删除用户 “${row.username}” 吗？`,
      '危险操作',
      { type: 'error' }
    )

    await userStore.deleteAdminUser(row.id)
    fetchUsers()
    ElMessage.success('删除成功')
  } catch (error) {
    console.log('取消删除')
  }
}

// 处理表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedUsers.value = selection
}

// 批量重置密码
const handleBatchResetPassword = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请先选择要重置密码的用户')
    return
  }

  try {
    const userNames = selectedUsers.value.map(user => user.username).join('、')
    
    await ElMessageBox.confirm(
      `<div style="text-align: left;">
        <p><strong>确定要批量重置用户密码吗？</strong></p>
        <p>选中的用户：${userNames}</p>
        <p>用户数量：${selectedUsers.value.length} 个</p>
        <p style="color: #e6a23c; margin-top: 10px;">
          <el-icon><Warning /></el-icon>
          重置后所有用户的密码将变为：<strong style="color: #f56c6c;">123456</strong>
        </p>
        <p style="color: #909399; font-size: 12px; margin-top: 8px;">
          请提醒用户及时修改密码以确保账户安全
        </p>
      </div>`,
      '批量重置密码确认',
      { 
        type: 'warning',
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确认重置',
        cancelButtonText: '取消',
        customClass: 'reset-password-dialog'
      }
    )

    // 显示加载状态
    const loadingInstance = ElMessage({
      message: `正在批量重置 ${selectedUsers.value.length} 个用户的密码...`,
      type: 'info',
      duration: 0,
      showClose: false
    })

    try {
      // 批量重置密码
      const promises = selectedUsers.value.map(user => 
        userStore.resetAdminUserPassword(user.id)
      )
      await Promise.all(promises)
      
      // 关闭加载提示
      loadingInstance.close()
      
      // 显示成功消息
      ElMessage({
        message: `成功重置 ${selectedUsers.value.length} 个用户的密码为 123456`,
        type: 'success',
        duration: 5000,
        showClose: true
      })
      
      // 清空选择
      selectedUsers.value = []
      
      // 刷新用户列表
      fetchUsers()
      
      // 记录操作日志
      console.log(`管理员批量重置了 ${selectedUsers.value.length} 个用户的密码`)
      
    } catch (apiError: any) {
      // 关闭加载提示
      loadingInstance.close()
      
      // 处理API错误
      const errorMessage = apiError?.response?.data?.message || 
                          apiError?.message || 
                          '批量重置密码失败，请稍后重试'
      ElMessage.error(errorMessage)
      console.error('批量重置密码API错误:', apiError)
    }
    
  } catch (error) {
    // 用户取消操作
    if (error !== 'cancel') {
      console.error('批量重置密码操作异常:', error)
      ElMessage.error('操作异常，请稍后重试')
    }
  }
}

onMounted(() => {
  fetchRoles() // 先获取角色列表
  fetchUsers() // 再获取用户列表
  
  // 监听角色数据更新事件
  window.addEventListener('roleDataUpdated', () => {
    fetchRoles()
  })
})
</script>

<style scoped lang="scss">
.user-management {
  padding: 24px;
  background: transparent;
  min-height: calc(100vh - 64px);

  // 页面头部
  .page-header {
    margin-bottom: 24px;

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      padding: 0;

      .title-section {
        .page-title {
          font-size: 28px;
          font-weight: 700;
          color: #1e293b;
          margin: 0 0 8px 0;
          letter-spacing: -0.025em;
        }

        .page-subtitle {
          font-size: 14px;
          color: #64748b;
          margin: 0;
        }
      }

      .header-actions {
        display: flex;
        gap: 12px;
        align-items: center;
        
        .selection-info {
          margin-right: 8px;
          
          .el-tag {
            border-radius: 6px;
            font-weight: 500;
          }
        }
        
        .el-button {
          font-weight: 500;
          border-radius: 8px;
          padding: 12px 24px;

          .el-icon {
            margin-right: 6px;
          }
          
          &.el-button--warning {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            border-color: #f59e0b;
            color: white;
            box-shadow: 0 2px 4px rgba(245, 158, 11, 0.3);
            
            &:hover {
              background: linear-gradient(135deg, #d97706 0%, #b45309 100%);
              border-color: #d97706;
              transform: translateY(-1px);
              box-shadow: 0 4px 8px rgba(245, 158, 11, 0.4);
            }
            
            &:disabled {
              background: #f3f4f6;
              border-color: #d1d5db;
              color: #9ca3af;
              transform: none;
              box-shadow: none;
            }
          }
        }
      }
    }
  }

  // 搜索区域
  .search-section {
    margin-bottom: 24px;

    .search-card {
      border-radius: 12px;
      border: 1px solid rgba(226, 232, 240, 0.8);
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 20px rgba(0, 0, 0, 0.04);

      .search-form {
        padding: 24px;

        .search-item {
          margin-bottom: 16px;

          .search-label {
            display: block;
            font-size: 14px;
            font-weight: 500;
            color: #374151;
            margin-bottom: 8px;
          }

          .el-input,
          .el-select {
            :deep(.el-input__wrapper) {
              border-radius: 8px;
              box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
              border: 1px solid #d1d5db;
              transition: all 0.3s ease;

              &:hover {
                border-color: #9ca3af;
              }

              &.is-focus {
                border-color: #3b82f6;
                box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
              }

              .el-input__inner {
                &::placeholder {
                  color: #9ca3af;
                }
              }
            }
          }
        }

        .search-actions {
          display: flex;
          gap: 12px;
          align-items: flex-end;
          height: 56px;

          .el-button {
            border-radius: 8px;
            font-weight: 500;
            padding: 10px 20px;

            .el-icon {
              margin-right: 6px;
            }
          }
        }
      }
    }
  }

  // 主要内容区域
  .content-section {
    .table-card {
      border-radius: 12px;
      border: 1px solid rgba(226, 232, 240, 0.8);
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 20px rgba(0, 0, 0, 0.04);
      overflow: hidden;

      :deep(.el-card__body) {
        padding: 0;
      }

      // 表格样式
      .el-table {
        :deep(.el-table__header-wrapper) {
          .el-table__header {
            th {
              border-bottom: 2px solid #e2e8f0;

              .cell {
                padding: 16px 12px;
              }
            }
          }
        }

        :deep(.el-table__body-wrapper) {
          .el-table__body {
            tr {
              &:hover {
                background: #f8fafc;
              }

              td {
                border-bottom: 1px solid #f1f5f9;

                .cell {
                  padding: 16px 12px;
                }
              }
            }
          }
        }

        // 用户信息样式
        .user-info {
          display: flex;
          align-items: center;
          gap: 12px;

          .user-avatar {
            border: 2px solid #e2e8f0;
            flex-shrink: 0;

            .el-icon {
              color: #9ca3af;
            }
          }

          .username {
            font-weight: 500;
            color: #1e293b;
          }
        }

        // 状态标签样式
        .status-tag {
          border-radius: 6px;
          font-weight: 500;
          padding: 4px 8px;
        }

        // 角色信息样式
        .role-info {
          .role-tag {
            border-radius: 6px;
            font-weight: 500;
            padding: 4px 8px;
          }
        }

        // 时间信息样式
        .time-info {
          display: flex;
          align-items: center;
          gap: 6px;
          color: #64748b;
          font-size: 13px;

          .time-icon {
            font-size: 14px;
          }
        }

        // 操作按钮样式
        .action-buttons {
          display: flex;
          gap: 8px;
          justify-content: center;

          .el-button {
            border-radius: 6px;
            font-weight: 500;
            padding: 6px 12px;

            .el-icon {
              margin-right: 4px;
            }

            &.el-button--primary {
              &.is-plain {
                &:hover {
                  background: #3b82f6;
                  border-color: #3b82f6;
                  color: white;
                }
              }
            }

            &.el-button--warning {
              &.is-plain {
                &:hover {
                  background: #f59e0b;
                  border-color: #f59e0b;
                  color: white;
                }
              }
            }

            &.el-button--success {
              &.is-plain {
                &:hover {
                  background: #10b981;
                  border-color: #10b981;
                  color: white;
                }
              }
            }

            &.el-button--info {
              &.is-plain {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                border-color: #667eea;
                color: white;
                font-weight: 600;
                box-shadow: 0 2px 4px rgba(102, 126, 234, 0.3);
                
                &:hover {
                  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
                  border-color: #5a6fd8;
                  transform: translateY(-1px);
                  box-shadow: 0 4px 8px rgba(102, 126, 234, 0.4);
                }
                
                .el-icon {
                  color: white;
                }
              }
            }
          }
        }
      }

      // 分页样式
      .pagination-wrapper {
        padding: 20px 24px;
        border-top: 1px solid #f1f5f9;
        background: #fafbfc;
        display: flex;
        justify-content: flex-end;

        :deep(.el-pagination) {
          .el-pager {
            li {
              border-radius: 6px;
              margin: 0 2px;
              font-weight: 500;

              &.is-active {
                background: #3b82f6;
                color: white;
              }
            }
          }

          .btn-prev,
          .btn-next {
            border-radius: 6px;
            margin: 0 2px;
          }
        }
      }
    }
  }

  // 对话框样式
  :deep(.user-dialog) {
    .el-dialog__header {
      padding: 24px 24px 0;

      .el-dialog__title {
        font-size: 20px;
        font-weight: 600;
        color: #1e293b;
      }
    }

    .el-dialog__body {
      padding: 24px;
    }

    .el-dialog__footer {
      padding: 0 24px 24px;
    }
  }

  // 表单样式
  .user-form {
    .el-form-item {
      margin-bottom: 24px;

      :deep(.el-form-item__label) {
        font-weight: 600;
        color: #374151;
        margin-bottom: 8px;
      }

      .el-input {
        :deep(.el-input__wrapper) {
          border-radius: 8px;
          box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
          border: 1px solid #d1d5db;
          transition: all 0.3s ease;

          &:hover {
            border-color: #9ca3af;
          }

          &.is-focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
          }

          .el-input__inner {
            &::placeholder {
              color: #9ca3af;
            }
          }
        }
      }

      .el-switch {
        :deep(.el-switch__core) {
          border-radius: 12px;
        }
      }
    }
  }

  // 对话框底部
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;

    .el-button {
      border-radius: 8px;
      font-weight: 500;
      padding: 10px 24px;
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .user-management {
    .search-section {
      .search-form {
        .search-actions {
          .el-button {
            width: 100%;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .user-management {
    padding: 16px;

    .page-header {
      .header-content {
        flex-direction: column;
        align-items: stretch;
        gap: 16px;

        .title-section {
          .page-title {
            font-size: 24px;
          }
        }

        .header-actions {
          .el-button {
            width: 100%;
            justify-content: center;
          }
        }
      }
    }

    .search-section {
      .search-form {
        padding: 20px;

        .search-item {
          margin-bottom: 16px;
        }

        .search-actions {
          height: auto;
          flex-direction: column;

          .el-button {
            width: 100%;
          }
        }
      }
    }

    .content-section {
      .table-card {
        .el-table {
          // 移动端表格样式调整
          .user-info {
            .username {
              font-size: 13px;
            }
          }

          .action-buttons {
            flex-direction: column;
            gap: 4px;

            .el-button {
              font-size: 12px;
              padding: 4px 8px;
            }
          }
        }

        .pagination-wrapper {
          padding: 16px;

          :deep(.el-pagination) {
            .el-pagination__total,
            .el-pagination__sizes,
            .el-pagination__jump {
              display: none;
            }
          }
        }
      }
    }

    .user-form {
      .el-row {
        .el-col {
          &:not(:last-child) {
            margin-bottom: 0;
          }
        }
      }
    }
  }
}

// 重置密码对话框自定义样式
:deep(.reset-password-dialog) {
  .el-message-box__content {
    padding: 20px;
    
    .el-message-box__message {
      p {
        margin: 8px 0;
        line-height: 1.5;
        
        &:first-child {
          margin-top: 0;
        }
        
        &:last-child {
          margin-bottom: 0;
        }
      }
      
      .el-icon {
        margin-right: 4px;
        vertical-align: middle;
      }
    }
  }
  
  .el-message-box__btns {
    padding: 10px 20px 20px;
    
    .el-button {
      border-radius: 6px;
      font-weight: 500;
      padding: 8px 20px;
      
      &.el-button--warning {
        background: #f56c6c;
        border-color: #f56c6c;
        color: white;
        
        &:hover {
          background: #f78989;
          border-color: #f78989;
        }
      }
    }
  }
}
</style>
